<template>
  <div class="contacts-box">
    <div class="contacts-parent">
      <!-- 多个关联校区 -->
      <template v-if="props.roleLists.length > 1">
        <TjCollapse
          v-for="(item, indexs) in props.roleLists"
          :key="item.id"
          v-model="currentItem"
          :borderless="'false'"
          expand-mutex
          @change="handlePanelChange($event, indexs)"
        >
          <TjCollapsePanel :value="indexs" :header="item.name">
            <template #expandIcon>
              <CaretDownIcon v-if="currentItem.length !== 0 && indexs === indexTJ" />
              <CaretRightIcon v-else />
            </template>
            <template v-for="(it, index) in item.childList" :key="it.id">
              <div
                class="role-li"
                :class="index === roleActive ? 'active-role' : null"
                @click="clickRoleChild(index)"
              >
                <div class="role-name">{{ it.name }}</div>
              </div>
            </template>
          </TjCollapsePanel>
        </TjCollapse>
      </template>
      <!-- 单个校区 -->
      <template v-else>
        <div v-for="(it, index) in props.roleLists[0].childList" :key="it.id">
          <div
            class="role-li"
            :class="index === roleActive ? 'active-role' : null"
            @click="clickRoleChild(index)"
          >
            <div class="role-name">{{ it.name }}</div>
          </div>
        </div>
      </template>
    </div>
    <div v-if="contactsChildList.length !== 0" class="contacts-child">
      <label v-if="maxCount * 1 !== 1" class="checkbox-labels">
        <TjCheckbox
          v-model:checked="allChecked"
          :indeterminate="indeterminate"
          :disabled="allDisabled"
          @change="clickAllHandler($event)"
        />
        <span>全选</span>
      </label>
      <div class="child-box">
        <template v-for="(item, index) in contactsChildList" :key="item.id">
          <div class="child-li">
            <TjCheckbox
              v-model:checked="item.checked"
              :disabled="item.disabled"
              class="checked-box"
              @change="clickHandler($event, item, index)"
            >
              <div class="boxs">
                <img v-if="item.avatar" class="avatar" :src="item.avatar" alt="" />
                <img v-else class="avatar" src="@/assets/img/oa-img-default.png" alt="" />
                <TjPopup
                  class="placement top center"
                  :disabled="item.username.length > 12 ? false : true"
                  :content="item.username"
                  placement="top"
                  :overlay-style="{ maxWidth: '215px' }"
                  show-arrow
                  destroy-on-close
                >
                  <div class="user-name">{{ item.username }}</div>
                </TjPopup>
              </div>
            </TjCheckbox>
          </div>
        </template>
      </div>
    </div>
    <template v-else>
      <div v-if="currentItem.length === 0" class="no-child">
        <img src="../../../../assets/img/default_add_img_zujian@2x.png" alt="" />
        <div class="span">请先选择校区</div>
      </div>
      <div v-else class="no-child">
        <img src="../../../../assets/img/default_search_img_people@2x.png" alt="" />
        <div class="span">暂无成员</div>
      </div>
    </template>
  </div>
</template>

<script>
export default {
  name: 'TabMenu'
};
</script>
<script setup>
import {
  defineProps,
  defineEmits,
  inject,
  ref,
  computed,
  onMounted,
  watch,
  defineExpose
} from 'vue';
import { CaretUpIcon, CaretDownIcon, CaretRightIcon } from 'tj-icons-vue';
import {
  TjSpace,
  TjCollapse,
  TjCollapsePanel,
  TjCheckboxGroup,
  TjCheckbox,
  TjPopup
} from 'tj-design-vue';
import store from '@/store';
const props = defineProps({
  height: {
    type: Number
  },
  roleLists: {
    // 角色数组
    type: Array,
    default: () => []
  },
  tabActive: {
    type: String // 部门还是角色
  }
});
const allDisabled = ref(false); // 全部禁选状态
let domHeight = ref(0); // 左侧组织dom高度
let domPeopleHeight = ref(0); // 右侧人dom高度
const roleActive = ref(0); // 选中角色idnex
const currentItem = ref([]); // 折叠面板绑定值
const contactsChildList = ref([]); // 选中当前角色下的人

onMounted(() => {
  setTimeout(() => {
    domHeight.value = store.state.user.contactsHeight + 'px';
    domPeopleHeight.value = store.state.user.contactsHeight - 38 + 'px';
  });
  const storage = JSON.parse(sessionStorage.getItem('tabStorage')); // 存贮展开值
  if (props.roleLists.length === 1) {
    // 没有关联校区, 默认显示第一租住
    if (storage) {
      roleActive.value = storage.two;
      currentItem.value = [storage.one];
    } else {
      currentItem.value = [0];
    }
    contactsChildList.value =
      props.roleLists[currentItem.value[0]].childList[roleActive.value].teacherList;
    mateSelectId(); // 处理选中id匹配状态
  } else {
    // 关联多个校区， 关闭所有层级
    console.log(storage);
    if (storage) {
      roleActive.value = storage.two;
      currentItem.value = [storage.one];
      contactsChildList.value =
        props.roleLists[currentItem.value[0]].childList[roleActive.value].teacherList;
      mateSelectId();
    } else {
      currentItem.value = [];
    }
  }
});

// 点击组织（斧头帮，兴隆学校）
const indexTJ = ref(0);
const handlePanelChange = (val, index) => {
  indexTJ.value = index;
  if (val.length === 0) {
    contactsChildList.value = [];
    sessionStorage.removeItem('tabStorage');
  } else {
    currentItem.value = val;
    roleActive.value = 0;
    sessionStorage.setItem('tabStorage', JSON.stringify({ one: currentItem.value[0], two: 0 })); // 存储角色选中值[two:当前选中角色， one:多个组织的时候有此值]
    contactsChildList.value = props.roleLists[val[0]].childList[roleActive.value].teacherList;
    mateSelectId(); // 处理选中id匹配状态
  }
};
// 点击角色（校长， 老师）
const clickRoleChild = val => {
  roleActive.value = val;
  console.log(props.roleLists);
  contactsChildList.value =
    props.roleLists[currentItem.value[0]].childList[roleActive.value].teacherList;
  console.log(contactsChildList.value);
  sessionStorage.setItem('tabStorage', JSON.stringify({ one: currentItem.value[0], two: val })); // 存储角色选中值[two:当前选中角色， one:多个组织的时候有此值]
  mateSelectId('click'); // 匹配选中id
};
// 选中列表
const selectList = inject('selectList');
function getChecked() {
  mateSelectId(); // 匹配选中id
}
defineExpose({
  getChecked
});
// 可选择最大人数
const maxCount = inject('maxCount');
// 是否禁用
const disabled = computed(() => selectList.value.length === maxCount.value);
const mateSelectId = type => {
  console.log('角色');
  contactsChildList.value.forEach(it => {
    it.checked = false;
    it.disabled = disabled.value;
  });
  selectList.value.forEach(item => {
    contactsChildList.value.forEach(it => {
      if (it.userId === item.userId) {
        it.disabled = false;
        it.checked = true;
      }
    });
  });
  allCheckedState();
};

// 添加或者删除选中人员
const addOrDelSelectHandler = inject('addOrDelSelectHandler');
const clickUserList = ref([]); // 选择当前人员数据
// 是否选中
const allChecked = computed(() => contactsChildList.value.length === allCheckedTrue.value.length);
const indeterminate = ref(false);
const getPeople = inject('getPeople'); // 添加或者删除选中人员 触发子组件事件选中对应的人
// 点击多选框
const clickHandler = (e, item, index) => {
  addOrDelSelectHandler(e, [contactsChildList.value[index]], 'userId');
  contactsChildList.value[index].checked = e;
  getPeople();
  mateSelectId();
};
// 点击全选框
const clickAllHandler = e => {
  allChecked.value = e;
  if (!e) indeterminate.value = false;
  if (contactsChildList.value.length >= maxCount.value * 1 - selectList.value.length) {
    // console.log(contactsChildList.value, 9099090);
    let list = [];
    contactsChildList.value.forEach((item, index) => {
      if (index < maxCount.value) {
        item.checked = e;
        // item.username = item.userName;
        list.push(item);
      } else {
        item.disabled = true;
        indeterminate.value = true;
        allDisabled.value = true;
      }
    });
    console.log(list);
    addOrDelSelectHandler(e, list, 'userId');
  } else {
    // console.log(2222);
    contactsChildList.value.forEach((item, index) => {
      item.checked = e;
      // item.username = item.userName;
      addOrDelSelectHandler(e, contactsChildList.value, 'userId');
    });
  }
  getPeople();
  // console.log(allChecked.value, indeterminate.value);
};
// 处理选中状态
const allCheckedTrue = ref([]); // 当前选中人集合
const allCheckedState = () => {
  let list = [];
  let disabledList = [];
  if (maxCount.value * 1 === selectList.value.length) {
    contactsChildList.value.forEach(item => {
      if (!item.checked) item.disabled = true;
    });
  }
  // console.log(contactsChildList.value);
  contactsChildList.value.forEach(item => {
    if (item.disabled) disabledList.push(item.disabled);
    if (item.checked) list.push(item.checked);
  });
  console.log(666666, disabledList);
  if (disabledList.length > 0) {
    allDisabled.value = true;
  } else {
    allDisabled.value = false;
  }
  allCheckedTrue.value = list;
  console.log(list);
  if (list.length === 0) {
    indeterminate.value = false;
    allChecked.value = false;
    // allDisabled.value = false;
    disabled.value = false;
    // console.log(allChecked, 9090909);
  } else {
    // console.log(6666, contactsChildList.value.length, allCheckedTrue.value.length);
    if (contactsChildList.value.length === allCheckedTrue.value.length) {
      indeterminate.value = false;
      allChecked.value = true;
    } else {
      if (allCheckedTrue.value.length !== 0) {
        console.log(555);
        indeterminate.value = true;
        allChecked.value = false;
      }
    }
  }
  // console.log(6666, contactsChildList.value);
  // console.log(allChecked.value, indeterminate.value);
};
</script>
<style lang="less">
.shuttle-pick-activate {
  color: v-bind(themeColor) !important ;
}

.shuttle-notActivat {
  color: rgba(0, 0, 0, 0.4) !important;
}
.shuttle-screen-pick-activate {
  background-color: v-bind(themeColor) !important;
  color: #fff;
}
</style>
<style lang="less" scoped>
.contacts-box {
  display: flex;
  .contacts-parent {
    overflow: auto;
    height: v-bind('domHeight');
    width: 49%;
    margin-right: 1%;
  }
  .child-box {
    overflow: auto;
    height: v-bind('domPeopleHeight');
  }
  .contacts-child {
    width: 50%;
    .checkbox-labels {
      width: 234px;
      padding: 8px;
      height: 38px;
      display: flex;
      align-items: center;
    }
    .picks-checkboxs {
      cursor: pointer;
      width: 16px;
      height: 16px;
      background: #ffffff;
      border: 1px solid rgba(186, 191, 197, 0.4);
      border-radius: 4px;
      margin-right: 8px;
    }
    .ss:indeterminate {
      color: aquamarine;
    }
    .ss:checked {
      background-color: red !important; /* 设置背景色为红色 */
    }
    .child-li:hover {
      background: #f5f6f7;
    }
    .child-li {
      display: flex;
      align-items: center;
      width: 249px;
      height: 38px;
      padding: 8px;
      // background: #f5f6f7;
      img {
        width: 32px;
        height: 32px;
        border-radius: 4px;
        margin-right: 12px;
      }
      .user-name {
        width: 164px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }
  }
  .no-child {
    margin: auto;
    img {
      margin: 0 auto;
      width: 164px;
      height: 164px;
    }
    .span {
      font-size: 14px;
      text-align: center;
      font-family: Microsoft YaHei, Microsoft YaHei-400;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.4);
    }
  }
}
/deep/ .tj-collapse-panel__header {
  padding: 8px !important;
}
/deep/ .tj-collapse-panel__content {
  padding: 4px 8px 8px 32px !important;
}
.role-li {
  width: 240px;
  height: 36px;
  padding: 7px 16px;
  cursor: pointer;
  font-size: 14px;
  font-family: Microsoft YaHei UI, Microsoft YaHei UI-400;
  font-weight: 400;
  text-align: LEFT;
  color: rgba(0, 0, 0, 0.8);
  .role-name {
    width: 145px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}
.active-role {
  background: #f5f6f7;
  border-radius: 2px;
  color: var(--tj-primary-color);
}
.tj-icon-caret-right {
  color: #8e959f !important;
}
input[class='picks-checkboxs'] {
  &:hover {
    cursor: pointer;
  }
  width: 16px;
  display: inline-block;
  text-align: center;
  line-height: 16px;
  position: relative;
  border-radius: 4px;
  border: none;
  box-sizing: border-box;
}
/deep/ .tj-icon-caret-down {
  color: #8e959f !important;
}
.checked-box {
  display: flex;
  align-items: center;
  .boxs {
    display: flex;
    align-items: center;
  }
}
/deep/ .tj-icon-caret-down:before {
  // font-size: 18px !important;
}
/deep/ .tj-icon-caret-right:before {
  // font-size: 18px !important;
}
/deep/ .tj-collapse-panel__header {
  padding: 7px 6px !important;
  padding-left: 7px !important;
}
</style>
